package io.gitee.zhangbinhub.admin.workflow.init

import io.gitee.zhangbinhub.acp.boot.init.AcpInitialization
import io.gitee.zhangbinhub.acp.core.common.CommonTools
import io.gitee.zhangbinhub.admin.common.constant.DbConstant
import io.gitee.zhangbinhub.admin.workflow.constant.WorkFlowConstant
import org.springframework.core.io.ClassPathResource
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.stereotype.Component
import java.nio.file.Files

@Component
class DataInitialization(private val jdbcTemplate: JdbcTemplate) : AcpInitialization {
    override val name: String
        get() = "Data Initialization"

    override val order: Int
        get() = 1

    private fun initTable() {
        ClassPathResource(
            "${DbConstant.SCHEMA_PATH}/${
                jdbcTemplate.dataSource?.connection?.metaData?.databaseProductName?.lowercase()
            }/${WorkFlowConstant.SCHEMA_FILE}"
        ).let { resource ->
            Files.readString(resource.file.toPath(), CommonTools.getDefaultCharset())
        }.apply {
            for (sql in this.split(";")) {
                if (sql.trim { it <= ' ' }.length > 10) {
                    jdbcTemplate.execute(sql)
                }
            }
        }
    }

    override fun doInit() {
        initTable()
    }
}